package com.example.zuoye;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.DialogPreference;
import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static android.media.CamcorderProfile.QUALITY_480P;
import static android.media.CamcorderProfile.get;
import static com.example.zuoye.R.id.question;
import static com.example.zuoye.R.id.visible;

public class ExamActivity extends AppCompatActivity {

    private int count;
    private int current;
    private int errorcount;
    private TextView questionview, explainview;
    private RadioGroup radioGroup; //四个选项框
    private RadioButton answerA;
    private RadioButton answerB;
    private RadioButton answerC;
    private RadioButton answerD;
    private Button btn_previous, btn_next; //下一题，上一题按钮



    private Handler mhandler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
           ResultSet rs1=(ResultSet) msg.obj;

            new AlertDialog.Builder(ExamActivity.this).setTitle("温馨提示").setMessage("选择选项后立即出现结果，请认真思考，谨慎选择答案！").setPositiveButton("                                我先去复习一下下...", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ExamActivity.this.finish();
                }
            }).setNegativeButton("我已收到", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();

           final List<Question> list=new ArrayList<Question>(); //题库中的题
            final List<Integer> errorList=new ArrayList<Integer>();  //选错的题
            final List<Question> newList=new ArrayList<Question>(); //错题集

            try {
                while (rs1!=null&&rs1.next())
                {
                    Question q=new Question();
                    q.setId(rs1.getInt("id"));
                    q.setQuestion(rs1.getString("question"));
                    q.setAnswerA(rs1.getString("answerA"));
                    q.setAnswerB(rs1.getString("answerB"));
                    q.setAnswerC(rs1.getString("answerC"));
                    q.setAnswerD(rs1.getString("answerD"));
                    q.setAnswer(rs1.getInt("answer"));
                    q.setExplaination(rs1.getString("explaination"));
                    q.setSelectedAnswer(-1);
                    list.add(q);
            }
            }catch (SQLException e)
            {
                e.printStackTrace();
            }

              count=list.size();
              current=0;
              errorcount=0;

            Question q=(Question)list.get(current);
            //questionview.setText(q.getId());
            questionview.setText(q.getQuestion());
            answerA.setText(q.getAnswerA());
            answerB.setText(q.getAnswerB());
            answerC.setText(q.getAnswerC());
            answerD.setText(q.getAnswerD());

         btn_next.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 if(current<count-1)
                 {
                     explainview.setText("");
                     current ++;
                     Question q=list.get(current);
                     //questionview.setText(q.getId());
                     questionview.setText(q.getQuestion());
                     answerA.setText(q.getAnswerA());
                     answerB.setText(q.getAnswerB());
                     answerC.setText(q.getAnswerC());
                     answerD.setText(q.getAnswerD());
                    radioGroup.clearCheck(); //切换到下一个题时，用户的选项标记要清空
                 }
                 else  //当前题目为最后一题时，告知用户作答正确的数量和作答错误的数量，并询问用户是否要查看错题
                 {
                     for(int i=0;i<count;i++)
                     {
                         if(list.get(i).answer!=list.get(i).selectedAnswer)
                         {
                             errorList.add(i);
                         }
                     }
                     final Connection conn=Connection_Init();

                     if(errorcount==0)
                     {
                         new AlertDialog.Builder(ExamActivity.this).setTitle("提示").setMessage("恭喜您全部回答正确！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {
                                 ExamActivity.this.finish();
                             }
                         }).show();
                     }
                     else
                         {
                         new AlertDialog.Builder(ExamActivity.this).setTitle("提示").setMessage("总共" + count + "道题，您答对了" + (count - errorcount) + "道题目，答错了" + errorcount + "道题目。是否查看错题？")
                                 .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                     @Override
                                     public void onClick(DialogInterface dialog, int which) {
                                         dialog.dismiss();
                                     }
                                 }).setNegativeButton("查看错题", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {


                                 for (int i = 0; i < errorList.size(); i++) { //记录错题
                                     newList.add(list.get(errorList.get(i)));
                                 }
                                 list.clear(); //将之前的题目清空，来放置错题

                                 for (int i = 0; i < newList.size(); i++) {
                                     list.add(newList.get(i));
                                 }

                                 current = 0;
                                 count = list.size();
                                 Question q = list.get(current);
                                 questionview.setText(q.getQuestion());
                                 answerA.setText(q.getAnswerA());
                                 answerB.setText(q.getAnswerB());
                                 answerC.setText(q.getAnswerC());
                                 answerD.setText(q.getAnswerD());
                                 char b = (char) (q.answer + 'A' - 1);
                                 char c = (char) (q.selectedAnswer + 'A' - 1);
                                 explainview.setText(" 正确答案是：" + b + "\n 您选择的是：" + c + "\n  题目解析： " + q.explaination);
                                 explainview.setVisibility(View.VISIBLE);

                                 btn_next.setOnClickListener(new View.OnClickListener() {
                                     @Override
                                     public void onClick(View v) {

                                         if(current<count-1) {

                                             current++;
                                             explainview.setText("");
                                             Question q = list.get(current);
                                             //questionview.setText(q.getId());
                                             questionview.setText(q.getQuestion());
                                             answerA.setText(q.getAnswerA());
                                             answerB.setText(q.getAnswerB());
                                             answerC.setText(q.getAnswerC());
                                             answerD.setText(q.getAnswerD());
                                             char b = (char) (q.answer + 'A' - 1);
                                             char c = (char) (q.selectedAnswer + 'A' - 1);
                                             explainview.setText(" 正确答案是：" + b + "\n 您选择的是：" + c + "\n  题目解析： " + q.explaination);
                                             explainview.setVisibility(View.VISIBLE);
                                         }
                                         else {
                                             new AlertDialog.Builder(ExamActivity.this).setTitle("温馨提示").setMessage("这是错题本的最后一页啦，是否退出？")
                                                     .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                                                         @Override
                                                         public void onClick(DialogInterface dialog, int which) {
                                                             Intent intent=new Intent(ExamActivity.this,RecordActivity.class);
                                                            /* Date date = new Date();
                                                             SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                             String mydate = ft.format(date);*/
                                                             DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                                             Calendar cal = Calendar.getInstance();
                                                             String mydate=dateFormat.format(cal.getTime());
                                                             String record=errorcount+"";
                                                             intent.putExtra("record",record);
                                                             intent.putExtra("time",mydate);
                                                             startActivity(intent);
                                                             ExamActivity.this.finish();
                                                         }
                                                     }).setPositiveButton("我再回头看看...", new DialogInterface.OnClickListener() {
                                                 @Override
                                                 public void onClick(DialogInterface dialog, int which) {
                                                     dialog.dismiss();
                                                 }
                                             }).show();
                                         }
                                     }
                                 });
                             }
                         }).show();

                     }


                 }
             }
         });
            btn_previous.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(current>0)
                    {
                        current--;
                        Question q=list.get(current);
                        //questionview.setText(q.getId());
                        questionview.setText(q.getQuestion());
                        answerA.setText(q.getAnswerA());
                        answerB.setText(q.getAnswerB());
                        answerC.setText(q.getAnswerC());
                        answerD.setText(q.getAnswerD());
                        radioGroup.clearCheck(); //切换到下一个题时，用户的选项标记要清空
                    }
                    else
                    {
                        new AlertDialog.Builder(ExamActivity.this).setTitle("提示").setMessage("这是第一题，前面没有题目啦!")
                                .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).show();
                    }
                }
            });

            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId)  //判断用户选择了哪个选项
                {

                    Question q=list.get(current);

                    if(answerA.isChecked()==true)
                    {
                        list.get(current).selectedAnswer=1;
                    }
                    else if(answerB.isChecked()==true)
                    {
                        list.get(current).selectedAnswer=2;
                    }
                    else if(answerC.isChecked()==true)
                    {
                        list.get(current).selectedAnswer=3;
                    }
                    else if(answerD.isChecked()==true)
                    {
                        list.get(current).selectedAnswer=4;
                    }

                    if(q.answer==q.selectedAnswer)
                    {
                        Toast.makeText(ExamActivity.this,"恭喜你回答正确！",Toast.LENGTH_SHORT).show();
                        explainview.setText("  题目解析： "+q.explaination);
                        explainview.setVisibility(View.VISIBLE);

                    }
                    else if(q.selectedAnswer!=-1&&q.answer!=q.selectedAnswer)
                    {

                        Toast.makeText(ExamActivity.this,"回答错误！请查看解析，分析总结。",Toast.LENGTH_SHORT).show();
                        explainview.setText("  题目解析： "+q.explaination);
                        explainview.setVisibility(View.VISIBLE);

                        errorcount++;  //记录错题数
                    }
                }
            });
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam);

        radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
        questionview = (TextView) findViewById(R.id.questionview); //题目界面
        final RadioButton[] radioButtons = new RadioButton[4]; //定义选项组件
        answerA = (RadioButton) findViewById(R.id.answerA);
        answerB = (RadioButton) findViewById(R.id.answerB);
        answerC = (RadioButton) findViewById(R.id.answerC);
        answerD = (RadioButton) findViewById(R.id.answerD);
        explainview = (TextView) findViewById(R.id.explainview); //题目解析页面
        btn_next = (Button) findViewById(R.id.btn_next); //下一题按钮
        btn_previous = (Button) findViewById(R.id.btn_previous); //上一题按钮

        ResultSet rs=null;
        new Thread(new Runnable() {   //获取sql数据库是耗时操作，只能在线程中进行操作。
            @Override
            public void run() {
               final Connection conn=Connection_Init();
               ResultSet rs=getQuestion(conn);
                Message message=new Message();//消息对象
                message.what=0; //区分谁发的消息
                message.obj=rs;
                mhandler.sendMessage(message);
                //insertRecord(conn);

            }
        }).start();

    }


    public Connection Connection_Init()
    {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载驱动
            long in1 = System.currentTimeMillis();
            try {
                connection = DriverManager.getConnection(
                        "jdbc:mysql://10.21.151.218:3306/test?useUnicode=true&characterEncoding=utf8",
                        "root",
                        "root");// 输入连接参数
                System.out.println(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            System.out.println("连接耗时" + (end - in1));//连接耗时
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public void insertRecord(Connection conn)
    {
        PreparedStatement mPreparedStatement=null;
        try {
            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String mydate = ft.format(date);

            String sql = "insert into wrong values (?,?)";

            mPreparedStatement=conn.prepareStatement(sql);
            mPreparedStatement.setInt(1,errorcount);
            mPreparedStatement.setString(2,mydate);
            mPreparedStatement.execute();
            Toast.makeText(ExamActivity.this,"成功",Toast.LENGTH_LONG).show();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

   /* public void insertRecord(Connection conn)
    {
        try {
            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String mydate = ft.format(date);

            String sql = "insert into wrong (count,time) values (" + 90 + "," + "'mydate1 '" + ")";


            //insert into wrong (count,time) values(100,'mydate')
            Statement stmt = conn.createStatement();
            stmt.executeQuery(sql);
            Toast.makeText(ExamActivity.this,"成功",Toast.LENGTH_LONG).show();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }*/


    public ResultSet getQuestion(Connection conn) {

        ResultSet rs = null;
        try {
            String sql = "select * from question";
            Statement stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;

    }
}
